//
//  DDAddressManagerViewController.m
//  Dingdong
//
//  Created by 程强 on 16/11/11.
//  Copyright © 2016年 程强. All rights reserved.
//

#import "DDAddressManagerViewController.h"
#import "DDAddressTableCell.h"
#import "DDCreateAddressViewController.h"
#import "KSPickerView.h"
#import "DDUserManager.h"
#import "DDReceiptAddSet.h"
#import "UIAlertView+Click.h"
#import "DDCreateAddressViewController.h"
#import "MJRefresh.h"

@interface DDAddressManagerViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *addressTable;
@property (strong, nonatomic) DDUserManager *manager;
@property (strong, nonatomic) DDReceiptAddSet *addSet;
@property (strong, nonatomic) DDReceiptAddObj *defaultReceipt;
@property (assign, nonatomic) NSInteger currentPage;
@property (strong, nonatomic) UIView *noAddView;
@end

@implementation DDAddressManagerViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self headerRefresh];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [DDUserManager new];
    [self layoutAddressView];
}
- (void)layoutAddressView
{
    self.currentPage = 1;
    [self setRefresh];
}
- (void)noAddressView
{
    if (_noAddView) {
        return;
    }
    self.noAddView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    [self.view addSubview:_noAddView];
    _noAddView.backgroundColor = RGBColor(244, 244, 244);
    [_noAddView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.centerX.width.bottom.equalTo(self.view);
    }];
    
    UIView *contentView = [[UIView alloc]init];
    [_noAddView addSubview:contentView];
    contentView.backgroundColor = [UIColor whiteColor];
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.width.equalTo(_noAddView);
        make.top.equalTo(_noAddView).offset(15);
        make.height.equalTo(_noAddView).multipliedBy(0.5);
    }];
    
    KKLabel *titleLbl = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
        lbl.laText(@"You don't have any address infomation,",RGBColor(153, 153, 153),[UIFont systemFontOfSize:16.0],NSTextAlignmentCenter);
    }];
    [contentView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_noAddView).offset(60);
        make.width.centerX.equalTo(_noAddView);
        make.height.equalTo(@30);
    }];
    
    KKLabel *titleLbl2 = [[KKLabel alloc]initWithBlock:^(KKLabel *lbl) {
        lbl.laText(@"Add a rapidly",RGBColor(153, 153, 153),[UIFont systemFontOfSize:16.0],NSTextAlignmentCenter);
    }];
    [contentView addSubview:titleLbl2];
    [titleLbl2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.width.equalTo(_noAddView);
        make.top.equalTo(titleLbl.mas_bottom);
        make.height.equalTo(@30);
    }];
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setBackgroundImage:LoadImage(@"add_address_gray") forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(addAddressClick:) forControlEvents:UIControlEventTouchUpInside];
    [contentView addSubview:addBtn];
    [addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_noAddView);
        make.top.equalTo(titleLbl2.mas_bottom).offset(50);
        make.width.height.equalTo(@77);
    }];
}
- (void)hideNoAddressView
{
    [self.noAddView removeFromSuperview];
    self.noAddView = nil;
}
- (void)setRefresh
{
    weak_Self(self);
    MJRefreshHeader *header =[MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headerRefresh];
    }];
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footerRefresh];
    }];
    [self.addressTable setMj_header:header];
    [self.addressTable setMj_footer:footer];
}
- (void)headerRefresh
{
    weak_Self(self);
    [self fetchAddressListPull:YES complete:^{
        [weakSelf.addressTable.mj_header endRefreshing];
    }];
}
- (void)footerRefresh
{
    weak_Self(self);
    [self fetchAddressListPull:NO complete:^{
        [weakSelf.addressTable.mj_footer endRefreshing];
    }];
}
#pragma mark --- 获取收货地址列表
- (void)fetchAddressListPull:(BOOL)pull complete:(void(^)())block
{
    weak_Self(self);
    if (pull) {
        self.currentPage = 1;
    }
    [[self.manager receiveAddressListWithPage:self.currentPage pageSize:kPageSize]subscribeNext:^(id x) {
        if (pull) {
            weakSelf.addSet = x;
        }else{
            DDReceiptAddSet *set = x;
            [weakSelf.addSet.addressAry addObjectsFromArray:set.addressAry];
        }
        if (weakSelf.addSet.addressAry.count == 0) {
            [weakSelf noAddressView];
        }else{
            [weakSelf hideNoAddressView];
        }
        weakSelf.currentPage+=1;
        [weakSelf.addressTable reloadData];
    } error:^(NSError *error) {
        
    } completed:^{
        if (block) {
            block();
        }
    }];
}
- (void)setDefalutAddress:(NSNumber *)add_id complete:(void(^)())block
{
    [[self.manager setReceiveAddressDefault:add_id]subscribeNext:^(id x) {
        
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (void)deleteReceiptAddress:(NSNumber *)add_id complete:(void(^)())block
{
    [[self.manager deleteReceiptAddress:add_id]subscribeNext:^(id x) {
        
        if (block) {
            block();
        }
    } error:^(NSError *error) {
        
    } completed:^{
        
    }];
}
- (IBAction)addAddressClick:(id)sender
{
    DDCreateAddressViewController *vc = StoryBoardViewController(@"User", @"DDCreateAddressViewController");
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --- UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.addSet.addressAry.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *indentifier = @"AddressCell";
    
    DDAddressTableCell *cell = [tableView dequeueReusableCellWithIdentifier:indentifier];
    
    if (!cell) {
        cell = [[DDAddressTableCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:indentifier];
    }
    DDReceiptAddObj *obj = self.addSet.addressAry[indexPath.row];
    cell.receiverLbl.text = obj.name;
    cell.phoneLbl.text = obj.mobile;
    cell.addressLbl.text = [NSString stringWithFormat:@"%@,%@,%@,%@",obj.province,obj.city,obj.region,obj.addr];
    if (obj.def_addr.integerValue ==1) {
        cell.receiptDefaultBtn.selected = YES;
        self.defaultReceipt = obj;
    }else
        cell.receiptDefaultBtn.selected = NO;
    
    weak_Self(self);
    [cell editReceiptAddress:^{
        DDCreateAddressViewController *vc = StoryBoardViewController(@"User", @"DDCreateAddressViewController");
        vc.vcType = DingDongAddressControllerTypeEdit;
        vc.addObj = obj;
        [self.navigationController pushViewController:vc animated:YES];
    } delete:^{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Do you want to delete the address?" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        alert.delegate = self;
        [alert show];
        [alert click:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [[self.manager deleteReceiptAddress:obj.addr_id]subscribeNext:^(id x) {
                    [self showMessageHUD:@"Delete Success" delayHide:1.0];
                    [self.addSet.addressAry removeObject:obj];
                    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                } error:^(NSError *error) {
                    
                } completed:^{
                    
                }];
            }
        }];
    } setDefault:^{
        if (self.defaultReceipt == obj) {
            return ;
        }else{
            [self setDefalutAddress:obj.addr_id complete:^{
                obj.def_addr = @1;
                weakSelf.defaultReceipt.def_addr = @0;
                weakSelf.defaultReceipt = obj;
                [tableView reloadData];
            }];
        }

    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.clickBlock) {
        alertView.clickBlock(buttonIndex);
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
